package com.cms.util;


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import com.cms.entity.User;

/**
*@author:gang
*@version:
**/
@Component
public class PasswordUtil {
	//简单MD5加密
	public static String  getPassword(String password){return DigestUtils.md2Hex(password);}
	
	//
	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private String algorithmName = "md5";
	private final int hashIterations = 2;

	public void encryptPassword(User user) {
		// User对象包含最基本的字段Username和Password
		user.setSalt(randomNumberGenerator.nextBytes().toHex());
		 // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐
		String newPassword = new SimpleHash(algorithmName, user.getUserPassword(),ByteSource.Util.bytes(user.getSalt()), hashIterations).toHex();
		user.setUserPassword(newPassword);
	}
	//
	public String returnPassword(User user,String password) {
		 // 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐
		String newPassword = new SimpleHash(algorithmName, password,ByteSource.Util.bytes(user.getSalt()), hashIterations).toHex();
		return newPassword;
	}

}
